package com.example.demo.common.session;

import com.alibaba.fastjson.JSON;
import com.example.demo.common.constants.SessionContents;
import com.example.demo.model.HttpResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * TODO
 *
 * @author wuhong-016
 * @version v1.0.0
 * @time: 2021/6/3 18:24
 */
public class RedisSessionFilter implements Filter {

    @Autowired
    private SessionComponent sessionComponent;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String sessionId = request.getSession().getId();

        // 判断登录状态
        boolean isLogin = sessionComponent.isLogin(sessionId);

        // 未登录  返回
        if (!isLogin) {
            HttpServletResponse response = (HttpServletResponse) servletResponse;
            response401(response);
        }
    }

    private void response401(HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");

        try {
            response.getWriter().print(HttpResult.error(1, "用户未登录"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
